package cn.yunyichina.provider.bone.service.impl;

import cn.yunyichina.provider.bone.dao.CardWalletDao;
import cn.yunyichina.provider.bone.dao.SeekHelpDao;
import cn.yunyichina.provider.bone.entity.CardWallet;
import cn.yunyichina.provider.bone.entity.SeekHelp;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.page.PageInfo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhuxp on 2017/12/27.
 *
 * @param
 * @Descrition
 */
@Service
@Log4j
public class SeekHelpServiceImpl {

    private SimpleDateFormat simpleDateFormat  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private SeekHelpDao seekHelpDao;

    @Autowired
    private CardWalletDao cardWalletDao;

    @Resource
    private CardWalletServiceImpl cardWalletService;

    /**
     * 查询求助记录列表
     * yyt.bone.seek.help.list
     * @param data
     * @return
     */
    public Response listSeekHelp(String data){
        log.info("查询求助记录列表,请求listSeekHelp入参:"+data);
        Response response = new Response();
        Map<String, Object> result = new HashMap<>();
        try {
            SeekHelp seekHelp = JsonUtils.parseObject(data,SeekHelp.class);
            Map<String,Object> requstMap = JsonUtils.parseObject(data, Map.class);
            String pageNum = (String) requstMap.get("page_num");
            String pageSize = (String) requstMap.get("page_size");
            if(StringUtils.isNotBlank(pageNum)&&StringUtils.isNotBlank(pageSize)){
                PageInfo pageInfo = new PageInfo();
                long count = seekHelpDao.selectCount(seekHelp);
                pageInfo.setTotal(count);
                pageInfo.setPageNum(Integer.valueOf(pageNum));
                pageInfo.setPageSize(Integer.valueOf(pageSize));
                pageInfo.setPages((pageInfo.getTotal().intValue() + pageInfo.getPageSize() - 1) / pageInfo.getPageSize());
                List<SeekHelp> seekHelps = seekHelpDao.select(seekHelp,pageInfo);
                result.put("list",seekHelps);
                result.put("pageInfo",pageInfo);
                response.setResult(JsonUtils.toJsonString(result));
                response.setResultCodeAndMessage("0", "查询求助记录列表成功!");
                log.info("查询求助记录列表成功，result:"+JsonUtils.toJsonString(result));
            }else {
                List<SeekHelp> seekHelps = seekHelpDao.select(seekHelp);
                response.setResult(JsonUtils.toJsonString(seekHelps));
                response.setResultCodeAndMessage("0", "查询求助记录列表成功!");
                log.info("查询求助记录列表成功，result:"+JsonUtils.toJsonString(seekHelps));
            }
        }catch (Exception e){
            log.error("查询求助记录列表异常:"+e);
            response.setResultCodeAndMessage("-1","查询求助记录列表异常!");
        }
        return response;
    }

    /**
     * 查询求助记录明细
     * yyt.bone.seek.help.detail.query
     * @param data
     * @return
     */
    public Response querySeekHelpDetail(String data){
        log.info("查询求助记录明细,请求querySeekHelpDetail入参:"+data);
        Response response = new Response();
        try {
            SeekHelp seekHelp = JsonUtils.parseObject(data,SeekHelp.class);
            if(StringUtils.isBlank(seekHelp.getId())){
                response.setResultCodeAndMessage("-2","求助记录id不能为空!");
                return response;
            }
            SeekHelp result = seekHelpDao.selectById(seekHelp.getId());
            if(result == null){
                response.setResultCodeAndMessage("-2","求助记录不存在!");
                return response;
            }
            result.setCreatedTime(simpleDateFormat.format(simpleDateFormat.parse(result.getCreatedTime())));
            response.setResultCodeAndMessageAndResult("0","查询求组记录明细成功!",JsonUtils.toJsonString(result));
        }catch (Exception e){
            log.error("查询求助记录明细异常:"+e);
            response.setResultCodeAndMessage("-1","查询求助记录明细异常!");
        }
        return response;
    }

    /**
     * 删除求助记录
     * yyt.bone.seek.help.delete
     * @param data
     * @return
     */
    public Response deleteSeekHelp(String data){
        log.info("删除求助记录,请求deleteSeekHelp入参:"+data);
        Response response = new Response();
        try {
            SeekHelp seekHelp = JsonUtils.parseObject(data,SeekHelp.class);
            if(StringUtils.isBlank(seekHelp.getId())){
                response.setResultCodeAndMessage("-2","求助记录id不能为空!");
                return response;
            }
            SeekHelp result = seekHelpDao.selectById(seekHelp.getId());
            if(result == null){
                response.setResultCodeAndMessage("-2","求助记录不存在!");
                return response;
            }
            seekHelpDao.delete(result);
            log.info("删除求助记录成功,seekHelp:"+result);
            response.setResultCodeAndMessage("0","删除求助记录成功!");
        }catch (Exception e){
            log.error("删除求助记录异常:"+e);
            response.setResultCodeAndMessage("-1","删除求助记录异常!");
        }
        return response;
    }

    /**
     * 修改求助记录状态
     * yyt.bone.seek.help.status.update
     * @param data
     * @return
     */
    public Response updateSeekHelpStatus(String data){
        log.info("修改求助记录状态,请求updateSeekHelpStatus入参:"+data);
        Response response = new Response();
        try {
            SeekHelp seekHelp = JsonUtils.parseObject(data,SeekHelp.class);
            if(StringUtils.isBlank(seekHelp.getId())||seekHelp.getStatus()==null){
                response.setResultCodeAndMessage("-2","求助记录id或status不能为空!");
                return response;
            }
            SeekHelp result = seekHelpDao.selectById(seekHelp.getId());
            if(result == null){
                response.setResultCodeAndMessage("-2","求助记录不存在!");
                return response;
            }
            result.setStatus(seekHelp.getStatus());
            result.setUpdateTime(simpleDateFormat.format(new Date()));
            seekHelpDao.update(result);
            log.info("修改求助状态成功!"+result);
            response.setResultCodeAndMessage("0","修改求助记录状态成功!");
        }catch (Exception e){
            log.error("修改求助记录状态异常:"+e);
            response.setResultCodeAndMessage("-1","修改求助记录状态异常!");
        }
        return response;
    }

    /**
     * 新增求助记录
     * yyt.bone.seek.help.insert
     * @param data
     * @return
     */
    public Response insertSeekHelp(String data){
        log.info("新增求助记录,请求insertSeekHelp入参:"+data);
        Response response = new Response();
        try {
            SeekHelp seekHelp = JsonUtils.parseObject(data,SeekHelp.class);
            //初始状态 0:已提交 1：已完成
            seekHelp.setId(PKGenerator.generateId());
            seekHelp.setStatus((short) 0);
            seekHelp.setCreatedTime(simpleDateFormat.format(new Date()));
            seekHelp.setUpdateTime(simpleDateFormat.format(new Date()));
            if(StringUtils.isNotBlank(seekHelp.getCardWalletId())&&StringUtils.isBlank(seekHelp.getRemarks())||
                    StringUtils.isBlank(seekHelp.getCardWalletId())&&StringUtils.isNotBlank(seekHelp.getRemarks())) {
                return Response.failure("-1", "remark或card_wallet_id不能为空");
            }else if (StringUtils.isNotBlank(seekHelp.getCardWalletId())){
                log.info("新增求助记录insertSeekHelp->通过cardWalletId:" + seekHelp.getCardWalletId() + "获取卡包信息");
                CardWallet cardWallet = cardWalletDao.selectById(seekHelp.getCardWalletId());
                if (cardWallet == null) {
                    log.info("新增求助记录insertSeekHelp->通过cardWalletId:" + seekHelp.getCardWalletId() + "获取卡包信息不存在");
                    return Response.failure("-1", "卡包信息不存在");
                } else if (cardWallet.getUseCount() + 1 <= cardWallet.getTotalCount()) {
                    cardWallet.setUseCount(cardWallet.getUseCount() + 1).setStatus((short) 1).setUpdateTime(simpleDateFormat.format(new Date()));
                    log.info("新增求助记录insertSeekHelp->通过cardWalletId:" + seekHelp.getCardWalletId() + "更新获取卡包信息" + JSON.toJSONString(cardWallet));
                    cardWalletDao.update(cardWallet);
                }
            }
            seekHelpDao.insert(seekHelp);
            log.info("新增求助记录成功!"+seekHelp);
            response.setResultCodeAndMessageAndResult("0","新增求助记录成功!",JsonUtils.toJsonString(seekHelp));
        }catch (Exception e){
            log.error("新增求助记录异常:"+e);
            response.setResultCodeAndMessage("-1","新增求助记录异常!");
        }
        return response;
    }
}
